﻿using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core
{
    public static class AssembliesExtensions
    {

        /// <summary>
        /// 根据基类获取类型集合
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Type> GetTypesByBaseType<T>()
        {
          return AssembliesExtensions.UserAssemblies.SelectMany(a => a.GetTypes().Where(t => t.IsInterface == false && t.BaseType==(typeof(T)))).ToArray();
        }

        /// <summary>
        /// 获取用户自建的所有程序集
        /// </summary>
        public static List<Assembly> UserAssemblies
        {
            get
            {
                var list = new List<Assembly>();
                if (DependencyContext.Default == null)
                {
                    return null;
                }
                if (DependencyContext.Default.CompileLibraries == null)
                {
                    return null;
                }
                var libs = DependencyContext.Default.CompileLibraries.Where(lib => (!lib.Serviceable && (lib.Type == "project" || lib.Type == "reference")) || lib.Name.Contains("Cyss") || lib.Name.Contains("Api.Client") || lib.Name.Contains("Api.Dtos"));
                foreach (var lib in libs)
                {
                    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
                    list.Add(assembly);
                }
                return list;
            }
        }
    }
}
